<template>
  <a-select
    v-model:value="selectValue"
    allow-clear
    :virtual="false"
    :options="options"
    placeholder="请选择"
    class="min-w-[160px]"
    :field-names="{ label: 'chargeStdName', value: 'id' }"
    @select="onChange"
    @focus="onFocus"
  >
    <template v-if="loading" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script setup>
/**
 * @name:选择收费标准
 */
import { ref, onMounted, watch } from 'vue'
import { post } from '@/utils/request'

const loading = ref(true)
const options = ref([])
const selectValue = ref(null)
const emit = defineEmits(['update:value', 'select'])
const props = defineProps({
  value: {
    type: String,
    default: null
  },
  params: {
    type: Object,
    desc: '请求参数',
    default: () => {}
  },
  selectFirst: {
    type: Boolean,
    default: false
  },
  trigger: {
    desc: '请求数据时机init:初始化/focus:聚焦',
    type: String,
    default: 'init'
  }
})
watch(
  () => props.value,
  (val) => {
    if (val) {
      selectValue.value = val
    } else {
      selectValue.value = options.value[0]?.id
    }
  },
  {
    immediate: true
  }
)
const onChange = (value, option) => {
  selectValue.value = value
  emit('update:value', value)
  emit('select', option)
}

// 获取数据
const getData = async () => {
  loading.value = true
  if (options.value.length > 0) return
  const { data = [] } = await post('/operation/chargeStandard/getChargeStandardList', {
    ...props.params,
    status: '0',
    pyjm: '',
    pageNum: 1,
    pageSize: 999
  })
  loading.value = false
  options.value = data
  if (props.selectFirst && !props.value && data.length) {
    selectValue.value = data[0].id
    emit('update:value', data[0].id)
    emit('select', data[0])
  }
}
const onFocus = () => {
  props.trigger === 'focus' && getData()
}
onMounted(() => {
  props.trigger === 'init' && getData()
})
</script>
